package com.webguard.outlierdetection.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.core.type.TypeReference;
import com.webguard.outlierdetection.pojo.Result;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/traffic")
public class TrafficDataController {

    private static final String JSONL_FILE = "test-ddos.jsonl";

    @GetMapping("/filtered-data")
    public Result getFilteredTrafficData() {
        List<Map<String, Object>> filteredData = new ArrayList<>();
        ObjectMapper objectMapper = new ObjectMapper();

        try (InputStream inputStream = getClass().getClassLoader().getResourceAsStream(JSONL_FILE);
             BufferedReader reader = new BufferedReader(new InputStreamReader(Objects.requireNonNull(inputStream)))) {

            String line;
            while ((line = reader.readLine()) != null) {
                Map<String, Object> rawData = objectMapper.readValue(line, new TypeReference<>() {});

                // 选取有效字段
                Map<String, Object> data = new LinkedHashMap<>();
                data.put("destinationPort", rawData.get(" Destination Port"));
                data.put("flowDuration", rawData.get(" Flow Duration") + " ms");
                data.put("flowRate", rawData.get("Flow Bytes/s") + " MB/s");
                data.put("packetRate", rawData.get(" Flow Packets/s") + " p/s");
                data.put("synFlagCount", rawData.get(" SYN Flag Count"));
                data.put("rstFlagCount", rawData.get(" RST Flag Count"));
                data.put("ackFlagCount", rawData.get(" ACK Flag Count"));
                data.put("eventTime", generateRandomTime()); // 生成随机事件时间
                data.put("label", rawData.get(" Label")); // 异常种类

                filteredData.add(data);
            }

            // 随机选取 20 到 100 条数据
            int randomSize = new Random().nextInt(81) + 20;  // 随机生成一个 20 到 100 之间的数
            List<Map<String, Object>> randomData = getRandomSubset(filteredData, randomSize);

            return Result.success(randomData);
        } catch (IOException e) {
            return Result.error(e.getMessage());
        }
    }

    /**
     * 生成随机的事件时间（过去7天内）
     */
    private String generateRandomTime() {
        Random random = new Random();
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DAY_OF_YEAR, -random.nextInt(7)); // 过去7天随机一天
        calendar.set(Calendar.HOUR_OF_DAY, random.nextInt(24));
        calendar.set(Calendar.MINUTE, random.nextInt(60));
        calendar.set(Calendar.SECOND, random.nextInt(60));

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return sdf.format(calendar.getTime());
    }

    /**
     * 从列表中随机选取指定数量的元素
     *
     * @param list 数据列表
     * @param size 选取数量
     * @return 随机选取的子集
     */
    private List<Map<String, Object>> getRandomSubset(List<Map<String, Object>> list, int size) {
        Collections.shuffle(list);  // 打乱列表顺序
        return list.subList(0, Math.min(size, list.size())); // 返回前 'size' 条数据
    }
}
